<template>
	<el-dialog
     :visible.sync="priceDateShow"
		  title="设置价格日历"
		  width="70%"
		  style="margin-left: 100px;"
		>
    <div class="carMywrapper">
		<div class="type-radio">
			
			<el-form label-width="130px" :model="baseInfo"  ref="baseInfo">
				<el-form-item  label="选择时间周期：" >
					<el-radio v-model="dateType" :label="1">按周</el-radio>
			        <el-radio v-model="dateType" :label="2">按日期</el-radio>
					<div v-show="dateType == 1" class="pd-20 bg-f7">
						<el-date-picker
							v-model="date1"
							@change="dateRangeChange"
							type="daterange"
							format="yyyy-MM-dd"
							value-format="yyyy-MM-dd"
							placeholder="选择日期范围">
						</el-date-picker>
						<el-checkbox-group v-model="checkList" @change="checkChange" class="mt-10" >
							<el-checkbox :label="1">每周一</el-checkbox>
							<el-checkbox :label="2">每周二</el-checkbox>
							<el-checkbox :label="3">每周三</el-checkbox>
							<el-checkbox :label="4">每周四</el-checkbox>
							<el-checkbox :label="5">每周五</el-checkbox>
							<el-checkbox :label="6">每周六</el-checkbox>
							<el-checkbox :label="0">每周日</el-checkbox>
						  </el-checkbox-group>
					</div>
					<div v-show="dateType ==2"  class="pd-20 bg-f7">
						<el-date-picker
							v-model="date2"
							@change="datesChange"
							type="dates"
							format="yyyy-MM-dd"
							value-format="yyyy-MM-dd"
							placeholder="选择日期">
						</el-date-picker>
					</div>
				</el-form-item>
				<div>
					<el-row :gutter="24">
						<el-col :span="12">
							<el-form-item  label="价格：" prop="price"  label-width="200px"   :rules="{ required: true, message: '请输入价格', trigger: 'blur' }"  >
								<el-input
								v-model="baseInfo.price"
								type="number"
								min="0"
								size="small"
								style="width: 150px;"
							  />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item  label="库存：" prop="stock"  label-width="200px"   :rules="{ required: true, message: '请输入库存', trigger: 'blur' }" >
								<el-input
								v-model="baseInfo.stock"
								type="number"
								min="0"
								size="small"
								style="width: 150px;"
							  />
							</el-form-item>
						</el-col>
						
					</el-row>
				</div>
			</el-form>
		</div>
		<div class="footer">
			<el-button type="primary" class="btns" size="small" @click="cancel">取消</el-button>
			<el-button type="primary" class="btns" size="small" @click="subBtn">确定排期</el-button>
		</div>
  </div>
	</el-dialog>
</template>
<script>

	import SettingMer from "@/libs/settingMer";
	import { getToken } from "@/utils/auth";
	import exportExcel from "@/utils/newToExcel.js";
	import {
	  importCard,
	  exportProductCard
	} from "@/api/product";
import { forEach } from "jszip/lib/object";
    export default {
			name: "addPriceDate",
			props:{
				addPriceType: {
					type: Number,
					default: function () {
						return 1;
					}
				},
				dateArr: {
					type: Array,
					default: []
				},
			
				svip_price_type: {
					type: Number,
					default: function () {
						return 0;
					}
				},
				extension_type: {
					type: Number,
					default: function () {
						return 0;
					}
				},
            },
			data(){
				return {
					priceDateShow: false,
					date1: [],
					date2: [],
					dateList: [],
					dateType: 1,
					checkList: [],
					finalDataList: [],
					baseInfo: {
						price: '',
		
						stock: '',
					}
				}
			},
			computed: {
				// cardUrl() {
				// 	return (
				// 		SettingMer.https +
				// 		`/upload/image/file`
				// 	);
				// }
			},
			created() {
			  this.dateList = this.dateArr;
			  console.log(' this.dateList', this.dateArr)
			},
			mounted() {
			},
      methods:{
		datesChange(e){
			this.dateList = e;
		},

		dateRangeChange(e){
			this.dateList =  this.filterDatesByWeekdays(this.date1, this.checkList);
		
		},
		checkChange(e){
			this.dateList =  this.filterDatesByWeekdays(this.date1, this.checkList);
	
		},
		checkEverChange(e){
			if(e == true){
				this.checkList = [1,2,3,4,5,6,0];
			} else {
				this.checkList = [];
			}
		},
		// 函数用于将字符串日期转换为 Date 对象，并获取星期几的数字表示（0-6）  
		getDayOfWeek(dateStr) {  
			const date = new Date(dateStr);  
			// 注意：getDay() 方法返回的是 0（周日）到 6（周六）之间的整数  
			return date.getDay();  
		},
		
		// 筛选日期数组的函数  
		filterDatesByWeekdays(date, weekdays) {  
			const allDates = this.generateDateRange(date[0], date[1]);  
			const filteredDates = [];  
		
			for (let dateStr of allDates) {  
				const date = this.parseDate(dateStr);  
				const dayOfWeek = date.getDay(); // 注意：getDay() 返回 0（周日）到 6（周六）  
				// 由于 weekdays 数组是从 1 开始的，而 getDay() 是从 0 开始的，我们需要 +1 来匹配  
				if (weekdays.includes(dayOfWeek)) {  
					filteredDates.push(dateStr);  
				}  
			}  
	
			return filteredDates;  
		},  
		// 辅助函数，生成指定日期范围内的所有日期数组  
		generateDateRange(start, end) {  
			let arr = [];  
			let current = this.parseDate(start);  
			const endDate = this.parseDate(end);  
			
			while (current <= endDate) {  
				arr.push(current.toISOString().split('T')[0]); // 转换为 YYYY-MM-DD 格式的字符串  
				current.setDate(current.getDate() + 1);  
			}  
			
			return arr;  
		},
		// 辅助函数，将日期字符串转换为 Date 对象  
		parseDate(dateStr) {  
			return new Date(dateStr);  
		}, 
				
		subBtn(){
			var that = this;
			this.finalDataList = [];
			if(!that.dateList.length){
				return that.$message.error("请选择价格周期,或者选择日期范围不包含指定日期");
			}
			this.$refs['baseInfo'].validate(valid => {
				if (valid) {
					if(this.dateList.length){
						for(var i= 0; i < this.dateList.length; i++){
							this.finalDataList.push({
								date: this.dateList[i],
								price: this.baseInfo.price,
								stock:  this.baseInfo.stock,

							})
						}
		
					}
					console.log("that.dateList",that.dateList)
					console.log("this.finalDataList11",this.finalDataList)
					// 去除重复部分
					var flag = false;
					for(var i= 0; i < this.finalDataList.length; i++){
						const item = this.dateArr.find(function(element) {
								return that.finalDataList[i].date == element.date;  
							});

							if(item != undefined){
								flag = true
								this.finalDataList.splice(i,1);
							}
					}
					if(flag){
						return that.$message.error("请检查选择的价格周期,所选日期包含已经排期的日期");
					}
					// 然后再合并
					this.dateList= this.dateList.concat(this.finalDataList);
			
					
					console.log("this.finalDataList",this.finalDataList)
					if(!that.finalDataList.length){
						return that.$message.error("请检查选择的价格周期,所选日期包含已经排期的日期");
					}
					this.$emit('changePrice',{
						addPriceType: this.addPriceType,
						finalDataList: this.finalDataList,
						dateList: this.dateList
					})
					this.date1 = [];
					this.date2 = [];
					this.dateList = [];
					this.checkList = [];
					this.finalDataList = [];
					this.baseInfo  = {
								price: '',
	
								stock: '',

							}
					this.priceDateShow = false;
				
				}
				
			});
			
			
		},
		cancel(){
			this.date1 = [];
			this.date2 = [];
			this.dateList = [];
			this.checkList = [];
			this.finalDataList = [];
			this.baseInfo  = {
						price: '',
						stock: '',
		
					}
			this.priceDateShow = false;
		}
      }
    }
</script>

<style lang="scss" scoped>
	.width15{
		width: 150px;
	}
	::v-deep .el-radio__label{
		font-size: 13px;
	}
	.carMywrapper{
		.download{
			margin-left: 10px;
		}
		.stock-disk{
			margin: 10px 0 15px 0;
		}
		.scroll-virtual {
		  max-height: 320px;
		  overflow-y: auto;
		  margin-top: 10px;
		}
		.virtual-title {
		  width: 50px;
		}
		.deteal-btn {
		  color: #5179ea;
		  cursor: pointer;
		}
		.add-more {
		  margin-top: 20px;
			line-height: 32px;

		}
		.footer{
			display: flex;
			justify-content: flex-end;
			margin-top: 40px;
			button{
				margin-left: 10px;
			}
		}
	}
	::v-deep .el-input-group--append .el-input__inner{
		padding-right: 0;
	}
</style>
